//对象转查询字符串
function objToSearchStr(obj){
    let str = '';
    for(let key in obj){
        str += `${key}=${obj[key]}&`;
    }
    return str.slice(0,str.length-1);
}

//封装ajax函数
function ajax(method,url,params,cb){
    //1.创建请求对象
    let xhr = new XMLHttpRequest();
    //2.配置请求对象
    xhr.open(method,method == 'get' ? url + '?' + objToSearchStr(params) : url);
    //3.设置回调函数
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            cb(JSON.parse(xhr.responseText));
        }
    }   
    //先对post请求设置content-type请求头
    xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
    //4.发送请求
    xhr.send(method == 'get' ? null : objToSearchStr(params));
}
